package com.saunter.service.user;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saunter.extendMapper.UserExtendMapper;
import com.saunter.extendModel.SalaryExtend;
import com.saunter.extendModel.UserExtend;
import com.saunter.model.Salary;
import com.saunter.model.SalaryKey;
import com.saunter.model.User;
import com.saunter.service.JobService;
import com.saunter.service.SalaryKeyService;
import com.saunter.service.SalaryService;
import com.saunter.utils.ConfigProperties;
import com.saunter.utils.CookieUtils;
import com.saunter.utils.Util;
import com.saunter.utils.encrypt.Md5Encrypt;
import com.saunter.utils.exception.ExceptionManager;
import com.saunter.utils.response.CustomPage;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/8/16.
 */
@Service("userService")
public class UserService extends SuperUserService implements SuperUserServiceInterf {
    @Autowired
    private UserExtendMapper userExtendMapper;
    @Autowired
    private JobService jobService;
    @Autowired
    private SalaryService salaryService;
    @Autowired
    private SalaryKeyService salaryKeyService;
    @Resource
    private ExceptionManager exceptionManager;
    @Autowired
    private ConfigProperties configProperties;

    protected String createAdminJwt(String user_id) {
        return super.createAdminJwt("id_num", user_id);
    }
    public void removeCookie(HttpServletResponse response) {
        CookieUtils.removeUserCookie(response, "sid");
    }
    public Boolean checkPasswd(String id_num, String passwd) {
        User user = userExtendMapper.selectByPrimaryKey(id_num);
        if(null == user) {
            throw exceptionManager.create("Lg001");
        }
        return Md5Encrypt.encrypt(passwd).equals(user.getPasswd());
    }
    public Map<String, String> login(String id_num, String passwd) {
        User user = userExtendMapper.selectByPrimaryKey(id_num);
        Map<String, String> res = new HashMap<String, String>();

        if(null == user) {
            res.put("err_code", "Lg001");
        }else{
            if(Md5Encrypt.encrypt(passwd).equals(user.getPasswd())) {
                String user_id = user.getIdNum();
                res.put("sid", this.createAdminJwt(""+user_id));
            }else {
                res.put("err_code", "Lg002");
                throw exceptionManager.create("Lg002");
            }
        }
        return res;
    }

    public Boolean checkJobByJobId(Integer job_id) {
        if(null == job_id || "".equals(job_id.toString().trim())) {
            return false;
        }
        return null != jobService.getById(job_id);
    }
    public int add(User user) {
        if(null != userExtendMapper.selectByPrimaryKey(user.getIdNum())) {
            throw  exceptionManager.create("User001");
        }
        String user_phone = user.getPhone();
        String user_email = user.getEmail();
        int user_sex = user.getSex();
        Integer status = user.getStatus();
        if("" != user_phone && null != user_phone && !Util.verifyPhone(user_phone)) {
            throw exceptionManager.create("Prm_phone");
        }
        if("" != user_email && null != user_email && !Util.verifyEmail(user_email)) {
            throw exceptionManager.create("Prm_email");
        }
        if((null != status && 0 != status && 1 != status) || (1 != user_sex && 2 != user_sex)) {
            throw exceptionManager.create("Prm003");
        }
        if(!this.checkJobByJobId(user.getJobId())) {
            throw exceptionManager.create("Job001");
        }
        return userExtendMapper.insertSelective(user);
    }

    public int insertByMap(List<Map<String, String>> data, String password, int job_id) {
        if(!this.checkJobByJobId(job_id)) {
            throw exceptionManager.create("Job001");
        }
        return userExtendMapper.insertByMap(data, password, job_id);
    }

    public CustomPage<User> getAll(int current_page, int page_size) {
        PageHelper.startPage(current_page,page_size);
        List<User> users = userExtendMapper.getAll();
        return new CustomPage<User>(users);
    }

    public CustomPage<UserExtend> getAllAndJob(int current_page, int page_size, Map<String, Object> filters) {
        PageHelper.startPage(current_page,page_size);
        List<UserExtend> users = userExtendMapper.getAllAndJob(filters);
        return new CustomPage<UserExtend>(users);
    }
    public List<UserExtend> getAllAndJob(Map<String, Object> filters) {
        return userExtendMapper.getAllAndJob(filters);
    }
    public List<User> getUserByJob(int job_id) {
        return userExtendMapper.getByJob(job_id);
    }

    public int editUser(User new_user) {
        String email = new_user.getEmail();
        String passwd = new_user.getPasswd();
        String phone = new_user.getName();
        User old_user = userExtendMapper.selectByPrimaryKey(new_user.getIdNum());
        if(null == old_user) {
            throw exceptionManager.create("User002");
        }
        Integer new_user_job_id = new_user.getJobId();
        if(null != new_user_job_id && !this.checkJobByJobId(new_user_job_id)) {
            throw exceptionManager.create("Job001");
        }
        if(null != email && !Util.verifyEmail(email)) {
            throw exceptionManager.create("Prm_email");
        }
        if(null != passwd && !Util.verifyPasswordFormat(passwd)) {
            throw exceptionManager.create("Prm_password");
        }
        if(null != phone && "".equals(phone.trim())) {
            throw exceptionManager.create("Prm005");
        }
        if(null != passwd) {
            passwd = Md5Encrypt.encrypt(passwd);
            new_user.setPasswd(passwd);
        }
        if(null != phone && phone.equals(old_user.getPhone()) ||null != email && email.equals(old_user.getEmail()) || (null != passwd && passwd.equals(old_user.getPasswd()))){
            throw exceptionManager.create("Prm004");
        }
        return userExtendMapper.updateByPrimaryKeySelective(new_user);
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int deleteById(String id_num) {
        if(null == userExtendMapper.selectByPrimaryKey(id_num)) {
            throw exceptionManager.create("User002");
        }
        int res_delete_user = userExtendMapper.deleteByPrimaryKey(id_num);
        int res_delete_salary = salaryService.deleteByUserIdNum(id_num);
        return res_delete_user;
    }

    public int setPasswd(String id_num, String passwd) {
        if(null == userExtendMapper.selectByPrimaryKey(id_num)) {
            throw exceptionManager.create("User002");
        }
        return userExtendMapper.setPasswd(id_num, Md5Encrypt.encrypt(passwd));
    }

    public User getByIdNum(String id_num) {
        return userExtendMapper.selectByPrimaryKey(id_num);
    }

    public List<String> getIdNumByIdNum(List<String> id_nums) {
        return userExtendMapper.getIdNumByIdNum(id_nums);
    }

    public CustomPage<SalaryExtend> getSalary(int current_page, int page_size, String id_num, String date_start, String date_end) {
        Map<String, Object> filters = new HashMap<String, Object>();
        filters.put("id_num", id_num);
        filters.put("date_start", date_start);
        filters.put("date_end", date_end);
        filters.put("status", 1);

        CustomPage<SalaryExtend> salary_data = salaryService.getAll(current_page, page_size, filters);
        salary_data.setData(salaryService.formatSalaryData(salary_data.getList()));

        return salary_data;
    }
    public List<Map<String, Object>> getSalaryKey() {
        List<SalaryKey> salary_keys = salaryKeyService.getAllShow();
        List<Map<String, Object>> format_salary_keys = new ArrayList<Map<String, Object>>();
        Map<String, Object> format_salary_key;
        for(SalaryKey salaryKey : salary_keys) {
            format_salary_key = new HashMap<String, Object>();
            format_salary_key.put("idKey", salaryKey.getIdKey());
            format_salary_key.put("label", salaryKey.getLabel());
            format_salary_key.put("remark", salaryKey.getRemark());
            format_salary_keys.add(format_salary_key);
        }
        return format_salary_keys;
    }

    public Map<String, Object> getSelf(String id_num) {
        if(null == id_num) return null;
        boolean show_user_job = configProperties.isShow_user_job();
        User user;
        if(show_user_job) {
            Map<String, Object> filter = new HashMap<String, Object>();
            filter.put("id_num", id_num);
            PageHelper.startPage(1, 1);
            List<UserExtend> users = userExtendMapper.getAllAndJob(filter);
            user = users.get(0);
        }else {
            user = userExtendMapper.selectByPrimaryKey(id_num);
        }
        if(null != user) {
            Map<String, Object> user_info = new HashMap<String, Object>();
            user_info.put("id_num", id_num);
            user_info.put("name", user.getName());
            user_info.put("phone", user.getPhone());
            user_info.put("email", user.getEmail());
            user_info.put("birthdate", user.getBirthdate().toString());
            if(show_user_job) {
                user_info.put("job", ((UserExtend)user).getJobStr());
            }
            return user_info;
        }else {
            return null;
        }
    }
}
